// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.Payable;
import com.fowo.api.entity.PayableProduct;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.DbOrganizationMapper;
import com.fowo.api.mapper.PayableMapper;
import com.fowo.api.mapper.PayableProductMapper;
import com.fowo.api.mapper.ProductMapper;
import com.fowo.api.mapper.SupplierMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.db.organization.DbOrganizationItemVo;
import com.fowo.api.model.db.organization.DbOrganizationSearchParamPo;
import com.fowo.api.model.payable.PayableAndPayableProductImportPo;
import com.fowo.api.model.payable.PayableBatchPushJinideAction;
import com.fowo.api.model.payable.PayableExcelPo;
import com.fowo.api.model.payable.PayableImportPo;
import com.fowo.api.model.payable.PayableItemVo;
import com.fowo.api.model.payable.PayableMarkCheckoutAction;
import com.fowo.api.model.payable.PayablePayableApproveAction;
import com.fowo.api.model.payable.PayablePushJinideAction;
import com.fowo.api.model.payable.PayableRevocationAction;
import com.fowo.api.model.payable.PayableSearchParamPo;
import com.fowo.api.model.payable.PayableVo;
import com.fowo.api.model.payable.constant.PayableCategoryIdEnums;
import com.fowo.api.model.payable.constant.PayableProductTypeEnums;
import com.fowo.api.model.payable.constant.PayablePushStatusEnums;
import com.fowo.api.model.payable.constant.PayableSettlementStatusEnums;
import com.fowo.api.model.payable.product.PayableProductItemVo;
import com.fowo.api.model.payable.product.PayableProductSearchParamPo;
import com.fowo.api.model.product.ProductItemVo;
import com.fowo.api.model.product.ProductSearchParamPo;
import com.fowo.api.model.supplier.SupplierItemVo;
import com.fowo.api.model.supplier.SupplierSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.PayableProductService;
import com.fowo.api.service.PayableService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysDepartmentMapper;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDepartmentSearchParamPo;
import com.fowo.api.sys.model.SysDepartmentVo;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 应付单 服务实现基类
 * @author 蜂窝蜜造平台 配置人：王阳阳，沈友谅
 */
@Slf4j
@DataObjectType(Payable.class)
@DS("ds24")
public class PayableBaseServiceImpl
  extends ServiceImpl<PayableMapper, Payable>
  implements PayableService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("supplierIdSupplierName", "s.`supplier_name`");
      put("supplierIdSupplierFullName", "s.`supplier_full_name`");
      put("warehouseName", "w.`name`");
      put("settlementOrgName", "do.`name`");
      put("payOrgName", "sd.`name`");
      put("purchasesOrgName", "do2.`name`");
      put("preparedByName", "su.`name`");
      put("verifierName", "su2.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected PayableService self;

  @Resource
  protected PayableProductService payableProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected SupplierMapper supplierMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected DbOrganizationMapper dbOrganizationMapper;

  @Resource
  protected SysDepartmentMapper sysDepartmentMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  private PayableProductMapper childMapper;

  @Resource
  protected ProductMapper productMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected PayableRevocationAction payableRevocationAction;

  @Autowired(required = false)
  protected PayableBatchPushJinideAction payableBatchPushJinideAction;

  @Autowired(required = false)
  protected PayableMarkCheckoutAction payableMarkCheckoutAction;

  @Autowired(required = false)
  protected PayablePushJinideAction payablePushJinideAction;

  @Autowired(required = false)
  protected PayablePayableApproveAction payablePayableApproveAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Resource
  protected Validator validator;

  /**
   * 创建应付单
   * @param model 应付单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(PayableVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Payable entity = new Payable();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getPushStatus() == null) {
      entity.setPushStatus("0");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getPayCode())) {
      entity.setPayCode(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "Payable.payCode")
        )
      );
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return entity.getId();
    }
    throw new Exception("应付单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 应付单
   */
  protected void updateAllChilds(PayableVo model) throws Exception {
    if (model.getProductltem() != null) {
      payableProductService.saveAllByParentPayable(
        model.getId(),
        model.getProductltem()
      );
    }
  }

  /**
   * 更新应付单
   * @param model 应付单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(PayableVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Payable entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("应付单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "supplierId",
      "totalNum",
      "warehouse",
      "createTime",
      "createUser",
      "lastUpdateTime",
      "lastUpdateUser",
      "settlementOrg",
      "purchasesOrg",
      "businessDate",
      "totalAmount",
      "remarks",
      "preparedBy",
      "verifier"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(entity.getId());
      return true;
    }
    return false;
  }/**
   * 更新应付单（带空值）
   * @param model 应付单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(PayableVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Payable entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("应付单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(Payable::getLastUpdateTime, model.getLastUpdateTime())
      .set(Payable::getLastUpdateUser, model.getLastUpdateUser())
      .set(Payable::getSettlementDate, model.getSettlementDate())
      .set(Payable::getRejectRemark, model.getRejectRemark())
      .set(Payable::getSettlementStatus, model.getSettlementStatus())
      .set(Payable::getCategoryId, model.getCategoryId())
      .eq(Payable::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
      baseMapper.updateCalcFields(model.getId());
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(PayableSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 商品(productltem) 对应的对象
    PayableProductSearchParamPo productltemSearchParam =
      new PayableProductSearchParamPo();
    productltemSearchParam.setDisableDataPremissions(true);
    productltemSearchParam.setParentPayableInList(ids);
    PayableProductMapper localPayableProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(PayableProductMapper.class);
    productltemSearchParam.applySqlSegments();
    List<Long> productltemIdList = localPayableProductMapper.searchIds(
      productltemSearchParam
    );
    if (!productltemIdList.isEmpty()) {
      PayableProductService localPayableProductService = ContextHolder
        .getApplicationContext()
        .getBean(PayableProductService.class);
      localPayableProductService.batchDelete(productltemIdList);
    }
  }

  /**
   * 删除应付单
   * @param id 应付单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除应付单
   * @param ids 应付单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<PayableImportPo> excelToImportRow(
    PayableImportPo row,
    Integer rowNumber,
    PayableVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<PayableImportPo> ir = new ImportRow<PayableImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<PayableImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new PayableVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, PayableImportPo.class);

    // 一般数据处理
    vo.setBusinessDate(SheetUtils.tryToDate(row.getBusinessDate()));
    SheetUtils.datePreviewFormat(row.getBusinessDate(), row::setBusinessDate);
    vo.setSettlementDate(SheetUtils.tryToDate(row.getSettlementDate()));
    SheetUtils.datePreviewFormat(
      row.getSettlementDate(),
      row::setSettlementDate
    );
    if (StringUtils.hasText(row.getStauts())) {
      List<SysDictAllItem> stautsItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "stauts",
          n -> sysDictService.getDictItems("SCM00020")
        );
      PayableVo finalVo = vo;
      stautsItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getStauts()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setStauts(i.getItemValue()),
          () ->
            ir.addError(
              "stauts",
              String.format(
                "必须为 %s 中之一",
                stautsItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    if (StringUtils.hasText(row.getPushStatus())) {
      vo.setPushStatus(PayablePushStatusEnums.toValue(row.getPushStatus()));
      if (vo.getPushStatus() == null) {
        ir.addError("pushStatus", "推送状态只能是：“未推送”, “成功”, “失败”");
      }
    }
    if (StringUtils.hasText(row.getProductType())) {
      vo.setProductType(PayableProductTypeEnums.toValue(row.getProductType()));
      if (vo.getProductType() == null) {
        ir.addError("productType", "产品类型只能是：“原材料”, “成品”, “加工”");
      }
    }
    if (StringUtils.hasText(row.getSettlementStatus())) {
      vo.setSettlementStatus(
        PayableSettlementStatusEnums.toValue(row.getSettlementStatus())
      );
      if (vo.getSettlementStatus() == null) {
        ir.addError("settlementStatus", "结款状态只能是：“未结账”, “已结账”");
      }
    }
    if (StringUtils.hasText(row.getCategoryId())) {
      vo.setCategoryId(PayableCategoryIdEnums.toValue(row.getCategoryId()));
      if (vo.getCategoryId() == null) {
        ir.addError("categoryId", "categoryId只能是：“低客单价”, “高客单价”");
      }
    }
    // 处理关联字段“供应商”
    if (
      !SheetUtils.isBlank(row.getSupplierIdSupplierName()) &&
      SheetUtils.isBlank(row.getSupplierId())
    ) {
      SupplierSearchParamPo supplierIdSearchParam = new SupplierSearchParamPo();
      supplierIdSearchParam.setLimit(2); // 最大只返回二行记录
      supplierIdSearchParam.setSupplierNameEq(
        SheetUtils.trim(row.getSupplierIdSupplierName())
      );
      supplierIdSearchParam.applySqlSegments();
      List<SupplierItemVo> supplierIdMatches = supplierMapper.search(
        supplierIdSearchParam
      );
      if (supplierIdMatches.size() == 0) {
        ir.addError("supplierIdSupplierName", "未能在供应商中找到匹配的数据");
      } else if (supplierIdMatches.size() > 1) {
        ir.addError(
          "supplierIdSupplierName",
          "关联不唯一，在供应商中找到多个匹配的数据"
        );
      } else {
        vo.setSupplierId(supplierIdMatches.get(0).getId());
      }
    }
    // 处理关联字段“仓库”
    if (
      !SheetUtils.isBlank(row.getWarehouseName()) &&
      SheetUtils.isBlank(row.getWarehouse())
    ) {
      WarehouseSearchParamPo warehouseSearchParam =
        new WarehouseSearchParamPo();
      warehouseSearchParam.setLimit(2); // 最大只返回二行记录
      warehouseSearchParam.setNameEq(SheetUtils.trim(row.getWarehouseName()));
      warehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> warehouseMatches = warehouseMapper.search(
        warehouseSearchParam
      );
      if (warehouseMatches.size() == 0) {
        ir.addError("warehouseName", "未能在仓库即时库存中找到匹配的数据");
      } else if (warehouseMatches.size() > 1) {
        ir.addError(
          "warehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWarehouse(warehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“结算组织”
    if (
      !SheetUtils.isBlank(row.getSettlementOrgName()) &&
      SheetUtils.isBlank(row.getSettlementOrg())
    ) {
      DbOrganizationSearchParamPo settlementOrgSearchParam =
        new DbOrganizationSearchParamPo();
      settlementOrgSearchParam.setLimit(2); // 最大只返回二行记录
      settlementOrgSearchParam.setNameEq(
        SheetUtils.trim(row.getSettlementOrgName())
      );
      settlementOrgSearchParam.applySqlSegments();
      List<DbOrganizationItemVo> settlementOrgMatches =
        dbOrganizationMapper.search(settlementOrgSearchParam);
      if (settlementOrgMatches.size() == 0) {
        ir.addError("settlementOrgName", "未能在组织中找到匹配的数据");
      } else if (settlementOrgMatches.size() > 1) {
        ir.addError(
          "settlementOrgName",
          "关联不唯一，在组织中找到多个匹配的数据"
        );
      } else {
        vo.setSettlementOrg(settlementOrgMatches.get(0).getId());
      }
    }
    // 处理关联字段“付款组织”
    if (
      !SheetUtils.isBlank(row.getPayOrgName()) &&
      SheetUtils.isBlank(row.getPayOrg())
    ) {
      SysDepartmentSearchParamPo payOrgSearchParam =
        new SysDepartmentSearchParamPo();
      payOrgSearchParam.setLimit(2); // 最大只返回二行记录
      payOrgSearchParam.setNameEq(SheetUtils.trim(row.getPayOrgName()));
      payOrgSearchParam.applySqlSegments();
      List<SysDepartmentVo> payOrgMatches = sysDepartmentMapper.search(
        payOrgSearchParam
      );
      if (payOrgMatches.size() == 0) {
        ir.addError("payOrgName", "未能在部门中找到匹配的数据");
      } else if (payOrgMatches.size() > 1) {
        ir.addError("payOrgName", "关联不唯一，在部门中找到多个匹配的数据");
      } else {
        vo.setPayOrg(payOrgMatches.get(0).getId());
      }
    }
    // 处理关联字段“采购组织”
    if (
      !SheetUtils.isBlank(row.getPurchasesOrgName()) &&
      SheetUtils.isBlank(row.getPurchasesOrg())
    ) {
      DbOrganizationSearchParamPo purchasesOrgSearchParam =
        new DbOrganizationSearchParamPo();
      purchasesOrgSearchParam.setLimit(2); // 最大只返回二行记录
      purchasesOrgSearchParam.setNameEq(
        SheetUtils.trim(row.getPurchasesOrgName())
      );
      purchasesOrgSearchParam.applySqlSegments();
      List<DbOrganizationItemVo> purchasesOrgMatches =
        dbOrganizationMapper.search(purchasesOrgSearchParam);
      if (purchasesOrgMatches.size() == 0) {
        ir.addError("purchasesOrgName", "未能在组织中找到匹配的数据");
      } else if (purchasesOrgMatches.size() > 1) {
        ir.addError(
          "purchasesOrgName",
          "关联不唯一，在组织中找到多个匹配的数据"
        );
      } else {
        vo.setPurchasesOrg(purchasesOrgMatches.get(0).getId());
      }
    }
    // 处理关联字段“制单人”
    if (
      !SheetUtils.isBlank(row.getPreparedByName()) &&
      SheetUtils.isBlank(row.getPreparedBy())
    ) {
      SysUserSearch preparedBySearchParam = new SysUserSearch();
      preparedBySearchParam.setLimit(2); // 最大只返回二行记录
      preparedBySearchParam.setNameEq(SheetUtils.trim(row.getPreparedByName()));
      preparedBySearchParam.applySqlSegments();
      List<SysUserItemVo> preparedByMatches = sysUserMapper.search(
        preparedBySearchParam
      );
      if (preparedByMatches.size() == 0) {
        ir.addError("preparedByName", "未能在用户中找到匹配的数据");
      } else if (preparedByMatches.size() > 1) {
        ir.addError("preparedByName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setPreparedBy(preparedByMatches.get(0).getId());
      }
    }
    // 处理关联字段“审核人”
    if (
      !SheetUtils.isBlank(row.getVerifierName()) &&
      SheetUtils.isBlank(row.getVerifier())
    ) {
      SysUserSearch verifierSearchParam = new SysUserSearch();
      verifierSearchParam.setLimit(2); // 最大只返回二行记录
      verifierSearchParam.setNameEq(SheetUtils.trim(row.getVerifierName()));
      verifierSearchParam.applySqlSegments();
      List<SysUserItemVo> verifierMatches = sysUserMapper.search(
        verifierSearchParam
      );
      if (verifierMatches.size() == 0) {
        ir.addError("verifierName", "未能在用户中找到匹配的数据");
      } else if (verifierMatches.size() > 1) {
        ir.addError("verifierName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setVerifier(verifierMatches.get(0).getId());
      }
    }
    // 子表导入处理
    if (row.getProductltem() != null && !row.getProductltem().isEmpty()) {
      List<ImportRow<PayableAndPayableProductImportPo>> handledChildRows =
        new ArrayList<>();
      PayableProductItemVo childVo = new PayableProductItemVo();
      for (ImportRow<PayableAndPayableProductImportPo> childRowPo : row.getProductltem()) {
        final ImportRow<PayableAndPayableProductImportPo> childImportRow =
          excelToImportChildRow(
            ir,
            childRowPo.getRow(),
            childRowPo.getRowNumber(),
            vo,
            childVo,
            variables
          );
        handledChildRows.add(childImportRow);
      }
      row.setProductltem(handledChildRows);
    }

    return ir;
  }

  /**
   * 子表导入处理
   */
  protected ImportRow<PayableAndPayableProductImportPo> excelToImportChildRow(
    ImportRow<PayableImportPo> parentRow,
    PayableAndPayableProductImportPo row,
    Integer rowNumber,
    PayableVo parentVo,
    PayableProductItemVo vo,
    Map<String, Object> variables
  ) {
    ImportRow<PayableAndPayableProductImportPo> ir = new ImportRow<>();
    ir.setParentRowNumber(parentRow.getRowNumber());
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<PayableAndPayableProductImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new PayableProductItemVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, PayableAndPayableProductImportPo.class);

    // 一般数据处理
    vo.setNum(SheetUtils.tryToInteger(row.getNum()));
    vo.setLastUnitPrice(SheetUtils.tryToDecimal(row.getLastUnitPrice()));
    vo.setPrice(SheetUtils.tryToDecimal(row.getPrice()));
    vo.setLastCostPrice(SheetUtils.tryToDecimal(row.getLastCostPrice()));
    vo.setCostPrice(SheetUtils.tryToDecimal(row.getCostPrice()));
    vo.setMainUnitPrice(SheetUtils.tryToDecimal(row.getMainUnitPrice()));
    vo.setGramWeight(SheetUtils.tryToDecimal(row.getGramWeight()));
    vo.setGramWeightAmount(SheetUtils.tryToDecimal(row.getGramWeightAmount()));
    vo.setLaborCosts(SheetUtils.tryToDecimal(row.getLaborCosts()));
    vo.setAccessoriesPrice(SheetUtils.tryToDecimal(row.getAccessoriesPrice()));
    vo.setPriceTax(SheetUtils.tryToDecimal(row.getPriceTax()));
    vo.setSubtotal(SheetUtils.tryToDecimal(row.getSubtotal()));
    // 处理关联字段“商品”
    if (
      !SheetUtils.isBlank(row.getProductIdName()) &&
      SheetUtils.isBlank(row.getProductId())
    ) {
      ProductSearchParamPo productIdSearchParam = new ProductSearchParamPo();
      productIdSearchParam.setLimit(2); // 最大只返回二行记录
      productIdSearchParam.setNameEq(SheetUtils.trim(row.getProductIdName()));
      productIdSearchParam.applySqlSegments();
      List<ProductItemVo> productIdMatches = productMapper.search(
        productIdSearchParam
      );
      if (productIdMatches.size() == 0) {
        ir.addError("productIdName", "未能在产品管理中找到匹配的数据");
      } else if (productIdMatches.size() > 1) {
        ir.addError(
          "productIdName",
          "关联不唯一，在产品管理中找到多个匹配的数据"
        );
      } else {
        vo.setProductId(productIdMatches.get(0).getId());
      }
    }
    // 计算数据处理
    SheetUtils.calculateField(
      row,
      vo,
      "getValue('num') *getValue('price')",
      "subtotal"
    );
    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<PayableImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<PayableImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            PayableImportPo.class,
            PayableAndPayableProductImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(PayableImportPo row, AnalysisContext cxt) {
              PayableVo vo = new PayableVo();
              ImportRow<PayableImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<PayableImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<PayableImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      PayableVo vo = new PayableVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"单据编号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "payCode".equals(m.getField())
          )
      ) {
        vo.setPayCode(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "Payable.payCode")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      // 子表数据处理
      importChild(vo, row, i, variables);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  protected void importChild(
    PayableVo vo,
    ImportRow<PayableImportPo> row,
    int i,
    Map<String, Object> variables
  ) {
    if (
      row.getRow().getProductltem() == null ||
      row.getRow().getProductltem().isEmpty()
    ) {
      return;
    }
    for (ImportRow<PayableAndPayableProductImportPo> childRow : row
      .getRow()
      .getProductltem()) {
      PayableProductItemVo itemVo = new PayableProductItemVo();
      final ImportRow<PayableAndPayableProductImportPo> rowChild =
        excelToImportChildRow(
          row,
          childRow.getRow(),
          childRow.getRowNumber(),
          vo,
          itemVo,
          variables
        );
      itemVo.setId(childRow.getUpdateId());
      if (rowChild.getErrors() != null && rowChild.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            rowChild.getRowNumber(),
            rowChild.getJoinErrorMessage()
          )
        );
      }
      if (vo.getProductltem() == null) {
        vo.setProductltem(new ArrayList<>());
      }
      vo.getProductltem().add(itemVo);
    }
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    PayableSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.setChildMappingOption(
        new CustomExcelExport.ChildMappingOption()
          .setFieldName("productltem")
          .setChildPageSearch((parentRecord, current, pageSize) -> {
            PayableItemVo parent = (PayableItemVo) parentRecord;
            PayableProductSearchParamPo searchParamPo =
              new PayableProductSearchParamPo();
            searchParamPo.setCurrent(current);
            searchParamPo.setPageSize(pageSize);
            searchParamPo.setParentPayableEq(parent.getId());
            return payableProductService.pageSearch(searchParamPo);
          })
      );
      exportOptions.addFieldMappingOption(
        "productltem.parentPayable",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(
              ((PayableProductItemVo) r).getParentPayableSupplierName()
            )
          )
      );
      exportOptions.addFieldMappingOption(
        "productltem.productId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PayableProductItemVo) r).getProductIdName())
          )
      );
      exportOptions.addFieldMappingOption(
        "supplierId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PayableItemVo) r).getSupplierIdSupplierName())
          )
      );
      exportOptions.addFieldMappingOption(
        "warehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PayableItemVo) r).getWarehouseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "settlementOrg",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PayableItemVo) r).getSettlementOrgName())
          )
      );
      exportOptions.addFieldMappingOption(
        "purchasesOrg",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PayableItemVo) r).getPurchasesOrgName())
          )
      );
      exportOptions.addFieldMappingOption(
        "businessDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "settlementDate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> DateUtils.toDateString((Date) o))
      );
      exportOptions.addFieldMappingOption(
        "stauts",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00020")
      );
      exportOptions.addFieldMappingOption(
        "pushStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> PayablePushStatusEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "productType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> PayableProductTypeEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "preparedBy",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PayableItemVo) r).getPreparedByName())
          )
      );
      exportOptions.addFieldMappingOption(
        "verifier",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((PayableItemVo) r).getVerifierName())
          )
      );
      exportOptions.addFieldMappingOption(
        "settlementStatus",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            PayableSettlementStatusEnums.toLabel((String) o)
          )
      );
      exportOptions.addFieldMappingOption(
        "categoryId",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> PayableCategoryIdEnums.toLabel((String) o))
      );
      exportOptions.addStringFields(
        "formId.parentPayableSupplierName",
        "formId.productIdName",
        "formId.name",
        "formId.sku",
        "formId.remark",
        "payCode",
        "supplierIdSupplierName",
        "supplierIdSupplierFullName",
        "totalNum",
        "warehouseName",
        "settlementOrgName",
        "purchasesOrgName",
        "totalAmount",
        "stauts",
        "remarks",
        "pushStatus",
        "resultInfo",
        "productType",
        "preparedByName",
        "verifierName",
        "purchaseOrder",
        "warehouseSn",
        "settlementStatus",
        "categoryId"
      );

      String fileName = String.format(
        "应付单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> stautsItems = sysDictService.getDictItems("SCM00020");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<PayableExcelPo> items = new ArrayList<PayableExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<PayableItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<PayableItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (PayableItemVo item : list) {
        PayableExcelPo excel = new PayableExcelPo();
        BeanUtils.copyProperties(item, excel);
        if (item.getStauts() != null) {
          stautsItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getStauts()))
            .findFirst()
            .ifPresent(i -> excel.setStauts(i.getItemText()));
        }
        excel.setPushStatus(
          PayablePushStatusEnums.toLabel(item.getPushStatus())
        );
        excel.setProductType(
          PayableProductTypeEnums.toLabel(item.getProductType())
        );
        excel.setSettlementStatus(
          PayableSettlementStatusEnums.toLabel(item.getSettlementStatus())
        );
        excel.setCategoryId(
          PayableCategoryIdEnums.toLabel(item.getCategoryId())
        );

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "应付单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(PayableExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过供应商名称查询应付单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdBySupplierName(String supplierName) {
    return this.baseMapper.getIdBySupplierName(supplierName);
  }

  /**
   * 通过供应商名称查询应付单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsBySupplierName(List<String> list) {
    return this.baseMapper.getIdsBySupplierName(list);
  }

  /**
   * 通过应付单主键查询供应商名称
   */
  @Override
  public String getSupplierNameById(Long id) {
    return this.baseMapper.getSupplierNameById(id);
  }

  /**
   * 通过应付单主键查询供应商名称列表
   */
  @Override
  public List<String> getSupplierNameByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getSupplierNameByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("supplierName"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 应付单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public PayableVo getVoById(Long id) throws Exception {
    PayableVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    PayableProductSearchParamPo productltemSearchParamPo =
      new PayableProductSearchParamPo();
    productltemSearchParamPo.setParentPayable(id);
    productltemSearchParamPo.getExtendData().put("queryMode", "sub");
    productltemSearchParamPo.getExtendData().put("queryParent", "Payable");
    productltemSearchParamPo.applySqlSegments();
    vo.setProductltem(payableProductService.search(productltemSearchParamPo));

    return vo;
  }

  /**
   * 分页查询应付单
   * @param search 查询条件
   * @return 应付单分页查询结果
   */
  @Override
  public Page<PayableItemVo> pageSearch(PayableSearchParamPo search) {
    Page<PayableItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(PayableItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 应付单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'PayableOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<PayableItemVo>> searchOptions(
    PayableSearchParamPo search
  ) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询应付单
   * @param search 查询条件
   * @return 应付单列表查询结果
   */
  @Override
  public List<PayableItemVo> search(PayableSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询应付单最后更新时间
   * @param search 查询条件
   * @return 应付单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(PayableSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 返回满足搜索条件的统计信息
   * @param search 搜索参数
   */
  @Override
  public Map<String, Object> searchForStatistical(PayableSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchForStatistical(search);
  }

  /**
   * 打回
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打回操作"
  )
  @Override
  public void revocation(Long id) throws Exception {
    if (payableRevocationAction == null) {
      throw new Exception("此操作当前不可用");
    }
    payableRevocationAction.run(id);
  }

  /**
   * 批量推送
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了批量推送操作"
  )
  @Override
  public void batchPushJinide(List<Long> ids) throws Exception {
    if (payableBatchPushJinideAction == null) {
      throw new Exception("此操作当前不可用");
    }
    payableBatchPushJinideAction.run(ids);
  }

  /**
   * 标记已结账
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了标记已结账操作"
  )
  @Override
  public void markCheckout(List<Long> ids) throws Exception {
    if (payableMarkCheckoutAction == null) {
      throw new Exception("此操作当前不可用");
    }
    payableMarkCheckoutAction.run(ids);
  }

  /**
   * 推送金蝶
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了推送金蝶操作"
  )
  @Override
  public void pushJinide(Long id) throws Exception {
    if (payablePushJinideAction == null) {
      throw new Exception("此操作当前不可用");
    }
    payablePushJinideAction.run(id);
  }

  /**
   * 审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了审核操作"
  )
  @Override
  public void payableApprove(Long id) throws Exception {
    if (payablePayableApproveAction == null) {
      throw new Exception("此操作当前不可用");
    }
    payablePayableApproveAction.run(id);
  }

  /**
   * 取消审核
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了取消审核操作"
  )
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void notApprove(Long id) throws Exception {
    executeScriptEngine.callJsInResource(
      "scripts/Payable_notApprove.js",
      id,
      null,
      this
    );
  }
}
